import { Popconfirm, Input, List, Space, message } from "antd";
import { useModel } from "umi";
import { useReactive } from "ahooks";

import useServicer from "../../hooks/useServicer";

const AddServicerModal = ({ reloadData }) => {
    const { remoteData } = useModel("global");
    const { onCloseGlobalModal } = useModel("global.modal");
    const { loginInfo } = useModel("person.info");
    const { addServicer } = useServicer();

    const state = useReactive({
        orgainzationData: [],
        loading: false,
    });

    const setServicer = async (item) => {
        addServicer(item, (res) => {
            if (res) {
                message.success("成功添加服务组织");
                reloadData();
                onCloseGlobalModal();
            }
        });
    };

    const handleSearch = async (value) => {
        if (value) {
            state.loading = true;
            let res = await remoteData({
                object: "public-user-auth-center",
                serviceUrl: loginInfo.authCenterUrl,
                serviceName: "/api/v1/organization/searchFullName",
                params: { fullName: value },
            });
            state.orgainzationData = res || [];
            state.loading = false;
        } else {
            message.warning("名称不能为空");
        }
    };

    return (
        <Space direction="vertical" size={20} style={{ width: "100%" }}>
            <Input.Search placeholder="搜索组织名称" onSearch={handleSearch} allowClear enterButton />
            <List
                loading={state.loading}
                header={"组织列表"}
                bordered
                size="small"
                dataSource={state.orgainzationData}
                renderItem={(item) => (
                    <List.Item
                        actions={[
                            <Popconfirm title="确定要设置当前组织为务联服务组织吗?" placement="topRight" onConfirm={() => setServicer(item)}>
                                <a>设置为服务商</a>
                            </Popconfirm>,
                        ]}
                    >
                        {item.fullName}
                    </List.Item>
                )}
            />
        </Space>
    );
};

export default AddServicerModal;
